﻿// kaisite_Server.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <direct.h>
#include <thread>
#include <io.h>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include "log.h"
#include "PublicClass.h"
#include "ClassHead.h"
#include "amqp.h"
#include "framing.h"
#include "tcp_socket.h"
#include "ssl_socket.h"
#include "ImageFormat.h"

using namespace std;

#pragma  comment(lib, "Ws2_32.lib")
#pragma  comment(lib, "rabbitmq.4.lib")

#define MAXBUFFER 1024 * 1024 * 10//数据缓冲

DerivedLock  g_csFingerprintUpdata;

//报错回调函数
long __stdcall callback(_EXCEPTION_POINTERS* excp)
{
	return EXCEPTION_EXECUTE_HANDLER;
}
//通讯线程
DWORD WINAPI Thread_recv(LPVOID lpThreadParameter)
{
	PThreadParameter pData = (PThreadParameter)lpThreadParameter;
	string strLog = "客户端" + to_string(pData->SocketNum) + "：建立连接";
	SaveLog("main", strLog.c_str());
	//缓冲区初始化
	int charNum = 0;
	char* charBuffer = new char[MAXBUFFER];//接收数据缓冲区
	char* RecvBuffer = new char[MAXBUFFER];//接收数据
	char* SendBuffer = new char[MAXBUFFER];//发送数据
	//循环接收客户端通讯
	time_t begin = time(0);
	while (true)
	{
		memset(charBuffer, 0, MAXBUFFER);
		int size = recv(pData->SocketNum, charBuffer, MAXBUFFER, 0);
		if (size > 0)
		{
			/*{
				std::string  strRecv, strHex;
				strRecv.assign(charBuffer, size);
				spm_bytes_to_hex(strRecv, strHex, true);
				SaveLog("main", strHex.c_str());
			}*/

			memcpy_s(RecvBuffer + charNum, MAXBUFFER - charNum, charBuffer, MAXBUFFER - charNum);
			charNum += size;
			if (size >= MAXBUFFER - 1)
			{
				strLog = "客户端" + to_string(pData->SocketNum) + "：接收数据过长";
				SaveLog("main", strLog.c_str());
			}
			else if (size < 12)
			{
				strLog = "客户端" + to_string(pData->SocketNum) + "：接收数据过短";
				SaveLog("main", strLog.c_str());
			}
			else
			{
				strLog = "客户端" + to_string(pData->SocketNum) + "：接收到有效数据";
				SaveLog("main", strLog.c_str());
				int iOffBuff = 0;//数据偏移量
				char cBegin[3], cCode[5], cEnd[3];//数据包特殊标识字段
				char* cData = NULL;
				int iLen = 0;
				string  strFinger;
				memset(cBegin, 0, 3);
				memset(cCode, 0, 5);
				memset(cEnd, 0, 3);
				memcpy_s(cBegin, 2, RecvBuffer + iOffBuff, 2);
				iOffBuff += 2;
				if (strcmp(cBegin, "7B") == 0)
				{
					memcpy_s(cCode, 4, RecvBuffer + iOffBuff, 4);
					iOffBuff += 4;
					//if (strcmp(cCode, "1011") == 0) {
					if (strcmp(cCode, "1011") == 0 || strcmp(cCode, "1001") == 0 || strcmp(cCode, "1002") == 0 || strcmp(cCode, "1031") == 0 || strcmp(cCode, "1032") == 0) {
						iLen = ntohl(*(int32_t*)(RecvBuffer + iOffBuff));
					}else {
						memcpy_s(&iLen, 4, RecvBuffer + iOffBuff, 4);
					}

					iOffBuff += 4;
					if (iLen < 0 || iLen > 2147483647)
					{
						strLog = "客户端" + to_string(pData->SocketNum) + "：数据包长度异常";
						SaveLog("main", strLog.c_str());
					}
					else if (iLen > charNum)
					{
						continue;
					}
					else
					{
						cData = new char[iLen + 1];
						memset(cData, 0, iLen + 1);
						memcpy_s(cData, iLen, RecvBuffer + iOffBuff, iLen);
						strFinger.assign(RecvBuffer + iOffBuff, iLen);
						iOffBuff += iLen;
						memcpy_s(cEnd, 2, RecvBuffer + iOffBuff, 2);
						if (strcmp(cEnd, "7E") == 0)
						{
							strLog = "客户端" + to_string(pData->SocketNum) + "：收到命令" + cCode;
							SaveLog("main", strLog.c_str());
							//表格模板下载
							if (strcmp(cCode, "1001") == 0)
							{
								string strData = strFinger;
								//解析参数
                                vector<string>  DataList;
                                GetStrList(strData, "&", DataList);
								int DataNum = DataList.size();
								if (DataNum == 3)
								{
									string ProcessType = DataList[0].c_str();
									string ProcessSort = DataList[1].c_str();
									string Version = DataList[2].c_str();
									//处理表格模板数据
									cTableEdit* cTable = new cTableEdit(pData->SocketNum);
									char* strTableData = cTable->GetTableData(ProcessType, ProcessSort, Version);
									//int flag = send(pData->SocketNum, strTableData, strlen(strTableData), 0);
									std::string   strSend;
									int n32TableLen = strlen(strTableData);
									{
										char szBuf[8] = "";
										*(int32_t*)szBuf = htonl(n32TableLen);
										strSend = "7B";
										strSend.append("1001");
										strSend.append(szBuf, 4);
										strSend.append(strTableData, n32TableLen);
										strSend.append("7E");

									}
									int flag = send(pData->SocketNum, strSend.c_str(), strSend.size(), 0);
									delete cTable;
									delete[] strTableData;
								}
							}
							//表格模板上传
							else if (strcmp(cCode, "1002") == 0)
							{
								string strData = strFinger;
								//解析参数
                                vector<string>  DataList;
                                GetStrList(strData, "@", DataList);
								int DataNum = DataList.size();
								if (DataNum >= 3)
								{
									string TableData = DataList[0].c_str();
									string PaperData = DataList[1].c_str();
									string MainData = DataList[2].c_str();
									string ClientData = "";
									if (DataNum == 4)
										ClientData = DataList[3].c_str();
									//处理表格模板数据
									cTableEdit* cTable = new cTableEdit(pData->SocketNum);
									char* strTableData = cTable->SetTableData(TableData, PaperData, MainData, ClientData);
									//int flag = send(pData->SocketNum, strTableData, strlen(strTableData), 0);
									std::string   strSend;
									int n32TableLen = strlen(strTableData);
									{
										char szBuf[8] = "";
										*(int32_t*)szBuf = htonl(n32TableLen);
										strSend = "7B";
										strSend.append("1002");
										strSend.append(szBuf, 4);
										strSend.append(strTableData, n32TableLen);
										strSend.append("7E");
									}
									int flag = send(pData->SocketNum, strSend.c_str(), strSend.size(), 0);
									delete cTable;
									delete[] strTableData;
								}
							}
							//指纹版本比对更新
							else if (strcmp(cCode, "1011") == 0)
							{
								string  strResult, strData = strFinger;
								cFingerprint* ClassFingerprint = new cFingerprint(&g_csFingerprintUpdata);
								if (ClassFingerprint) {
									try {
										if (0 == ClassFingerprint->FingerprintVersion_Updata(strData, strResult)) {
											int flag = send(pData->SocketNum, strResult.c_str(), strResult.size(), 0);
											begin = time(0);//重置服务端十秒等待时间
										}
									}catch (...) {}
									delete  ClassFingerprint;
								}
							}
							//签字图片上传
							else if (strcmp(cCode, "1021") == 0)
							{
								SaveLog("main", "收到手写签字数据");
								string strData = cData;
								//接收完数据，通知客户端断开连接
								int flag = send(pData->SocketNum, "1", 1, 0);
								//解析参数
								string recordId = "";
								strCoding ClassCoding;
								cLibFather ClassFather;
								string strMQ = "";
                                vector<string>  DataList;
                                GetStrList(strData, "&", DataList);
								for (int i = 0; i < DataList.size(); i++)
								{
                                    vector<string>  KeyValue;
                                    GetStrList(DataList[i], "=", KeyValue);
									if (KeyValue[0] == "recordId" && KeyValue.size() > 1)
										recordId = KeyValue[1];
									if (strMQ.length() > 0)
										strMQ += ",";
									strMQ += "\"" + KeyValue[0] + "\":";
									if (KeyValue.size() > 1)
									{
										string strUTF8 = "";
										ClassCoding.GB2312ToUTF_8(strUTF8, KeyValue[1].c_str(), KeyValue[1].length());
										strMQ += "\"" + strUTF8 + "\"";
									}
                                    else{
                                        strMQ += "\"\"";
                                    }
								}
								//发送MQ消息
								PSendDataMQ pNew = new SendDataMQ();
								pNew->RoutingKey = ClassFather.GetRoutingKey(recordId);
								pNew->Data = "{" + strMQ + "}";
								pData->pLock->Lock();
								pNew->pNext = pData->pHeadMQ->pNext;
								pData->pHeadMQ->pNext = pNew;
								pData->pLock->Unlock();
							}
							//电子签名上传
							else if (strcmp(cCode, "1022") == 0)
							{
								SaveLog("main", "收到电子签名数据");
								string strData = cData;
								//接收完数据，通知客户端断开连接
								int flag = send(pData->SocketNum, "1", 1, 0);
							}
							//标签模板下载
							else if (strcmp(cCode, "1031") == 0)
							{
								string strData = strFinger;
								//读取标签模板数据
								cTableLabel* cTable = new cTableLabel(pData->SocketNum);
								char* strTableData = cTable->GetTableData(strData);
								//int flag = send(pData->SocketNum, strTableData, strlen(strTableData), 0);
								std::string   strSend;
								int n32TableLen = strlen(strTableData);
								{
									char szBuf[8] = "";
									*(int32_t*)szBuf = htonl(n32TableLen);
									strSend = "7B";
									strSend.append("1031");
									strSend.append(szBuf, 4);
									strSend.append(strTableData, n32TableLen);
									strSend.append("7E");
								}
								int flag = send(pData->SocketNum, strSend.c_str(), strSend.size(), 0);
								delete cTable;
								delete[] strTableData;
							}
							//标签模板更新
							else if (strcmp(cCode, "1032") == 0)
							{
								string strData = strFinger;
								//解析参数
								vector<string>  DataList;
								GetStrList(strData, "@", DataList);
								int DataNum = DataList.size();
								if (DataNum >= 2)
								{
									string TableData = DataList[0].c_str();
									string MainData = DataList[1].c_str();
									//处理标签模板数据
									cTableLabel* cTable = new cTableLabel(pData->SocketNum);
									char* strTableData = cTable->SetTableData(TableData, MainData);
									//int flag = send(pData->SocketNum, strTableData, strlen(strTableData), 0);
									std::string   strSend;
									int n32TableLen = strlen(strTableData);
									{
										char szBuf[8] = "";
										*(int32_t*)szBuf = htonl(n32TableLen);
										strSend = "7B";
										strSend.append("1032");
										strSend.append(szBuf, 4);
										strSend.append(strTableData, n32TableLen);
										strSend.append("7E");
									}
									int flag = send(pData->SocketNum, strSend.c_str(), strSend.size(), 0);
									delete cTable;
									delete[] strTableData;
								}
							}
							//客户端提示断开连接
							else if (strcmp(cCode, "1000") == 0)
							{
								break;
							}
						}
						delete[] cData;
					}
				}
			}
		}
		else if (size == 0)
		{
			strLog = "客户端" + to_string(pData->SocketNum) + "：已主动断开连接";
			SaveLog("main", strLog.c_str());
			break;
		}
		else
		{
			time_t end = time(0);
			if (end - begin > 10)//建立连接后10秒内无数据进来，断开
			{
				strLog = "客户端" + to_string(pData->SocketNum) + "：10秒内未接收到数据";
				SaveLog("main", strLog.c_str());
				break;
			}
			else
				Sleep(100);
		}
	}
	int sleep = 1000;//延迟10秒后断开socket连接
	while (sleep--)
	{
		Sleep(10);
	}
	strLog = "客户端" + to_string(pData->SocketNum) + "：断开连接";
	SaveLog("main", strLog.c_str());
	closesocket(pData->SocketNum);
	delete[] SendBuffer;
	delete[] RecvBuffer;
	delete[] charBuffer;


	return 0;
}
//监听线程
DWORD WINAPI Thread_accept(LPVOID lpThreadParameter)
{
	PThreadParameter pData = (PThreadParameter)lpThreadParameter;
	string strLog = "服务端监听线程启动";
	SaveLog("主进程日志", strLog.c_str());
	char ServerIP[32];
	char ServerPort[32];
	//监听服务器IP
	memset(ServerIP, 0, 32);
	GetPrivateProfileString("SocketServer", "IP", "127.0.0.1", ServerIP, 32, "./config.ini");
	WritePrivateProfileString("SocketServer", "IP", ServerIP, "./config.ini");
	//监听服务器端口
	memset(ServerPort, 0, 32);
	GetPrivateProfileString("SocketServer", "Port", "8839", ServerPort, 32, "./config.ini");
	WritePrivateProfileString("SocketServer", "Port", ServerPort, "./config.ini");
	strLog = (string)"IP：" + ServerIP + "，Port：" + ServerPort;
	SaveLog("主进程日志", strLog.c_str());
	//初始化winsock2.dll
	WSADATA wsData;
	WORD wVersionRequested = MAKEWORD(2, 2);
	if (WSAStartup(wVersionRequested, &wsData) != 0)
	{
		SaveLog("主进程日志", "加载winsock2.dll失败！");
		return 0;
	}
	//创建套接字
	SOCKET sock_server;
	if ((sock_server = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
	{
		strLog = "创建套接字失败！错误代码：" + WSAGetLastError();
		SaveLog("主进程日志", strLog.c_str());
		WSACleanup();
		return 0;
	}
	//设置非阻塞模式
	unsigned long ul = 1;
	int ret = ioctlsocket(sock_server, FIONBIO, (unsigned long*)&ul);
	SaveLog("主进程日志", "监听线程设置非阻塞模式");
	//绑定ip和端口
	sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(ServerPort));
	inet_pton(AF_INET, ServerIP, &addr.sin_addr);//绑定本机
	if (SOCKET_ERROR == ::bind(sock_server, (SOCKADDR*)&addr, sizeof(sockaddr_in)))
	{
		strLog = "地址端口绑定失败！错误代码：" + WSAGetLastError();
		SaveLog("主进程日志", strLog.c_str());
		closesocket(sock_server);
		WSACleanup();
		return 0;
	}
	listen(sock_server, 0);//转为监听状态
	SaveLog("主进程日志", "监听线程开始监听");
	//主线程循环接收客户端连接
	while (1)
	{
		sockaddr_in addrClient;
		int len = sizeof(sockaddr_in);
		//接收成功返回与client通讯的socket
		SOCKET con = accept(sock_server, (SOCKADDR*)&addrClient, &len);
		if (con != INVALID_SOCKET)
		{
			//创建线程 传入与client通讯的套接字
			PThreadParameter pThreadData = new ThreadParameter;
			pThreadData->SocketNum = con;
			pThreadData->pHeadMQ = pData->pHeadMQ;
			pThreadData->pLock = pData->pLock;
			HANDLE hThread = CreateThread(NULL, 0, Thread_recv, (LPVOID)pThreadData, 0, NULL);
			CloseHandle(hThread);//关闭对线程的引用
		}
		Sleep(1);
	}
	closesocket(sock_server);
	WSACleanup();
	SaveLog("主进程日志", "监听线程关闭");
}

int main()
{
	//string strJson = "{\"id\":\"1717748895485792262\",\"type\":\"zgglz\"}";
	//cProcessChange ClassProcessChange(strJson);
	//ClassProcessChange.FindProcessData();
	//ClassProcessChange.UpdataTableProcess();
	//ClassProcessChange.UpdataBlankTable();

	//string strJson = "{\"id\":\"1730495822012833794\",\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":null,\"tenantDTO\":null,\"image\":null,\"currentRecordInfoList\":null,\"screens\":null,\"andOr\":null,\"code\":\"采购订单编号\",\"documentDate\":\"2023-12-01\",\"department\":{\"id\":\"1563061974827393026\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"parentId\":null,\"parentIds\":null,\"name\":null,\"sort\":null,\"children\":null,\"legalPerson\":null,\"code\":null,\"type\":null,\"grade\":null,\"address\":null,\"master\":null,\"phone\":null,\"useable\":null,\"departmentNum\":null,\"remarks\":null,\"productionUnit\":null},\"address\":{\"id\":\"1715255746370629634\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"address\":null,\"contactPerson\":null,\"phone\":null},\"orderCategory\":{\"id\":\"1719631600946917377\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"name\":null,\"prefix\":null},\"supplierDoc\":{\"id\":\"1715334963494055937\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"name\":null,\"outManufacturer\":null,\"shortName\":null,\"englishName\":null,\"taxId\":null,\"status\":null,\"buyerId\":null,\"bkAccountGroup\":null,\"currencyRateId\":null,\"payTermsId\":null,\"taxRateId\":null,\"openAccountBank\":null,\"bankAccount\":null,\"bankAccountName\":null,\"pricingMethod\":null,\"tradeClause\":null,\"deliveryWayId\":null,\"discountCategoryId\":null,\"companyAddress\":null,\"postcode\":null,\"companyWebsite\":null,\"dutyPerson\":null,\"phoneOne\":null,\"phoneTwo\":null,\"contactPerson\":null,\"faxOne\":null,\"faxTwo\":null,\"remarks\":null,\"type\":null,\"overProportion\":null,\"supplierClassificationId\":null,\"examineTime\":null,\"examineStatus\":null,\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"creatorOfficeName\":null,\"creatorOfficeId\":null,\"email\":null},\"purchaser\":{\"id\":\"1717751016593436674\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"name\":null,\"phone\":null,\"status\":null,\"officeId\":null,\"buyerId\":null,\"userId\":null,\"companyId\":null},\"shippingWay\":{\"id\":\"1714986098608713729\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"way\":null},\"currency\":{\"id\":\"1728965968679350273\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"name\":null,\"symbol\":null,\"digit\":null,\"remarks\":null},\"applicationsAmount\":null,\"exchangeRateId\":\"1\",\"taxRate\":{\"id\":\"1719298451308511233\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"taxRate\":null,\"remarks\":null},\"paymentWay\":{\"id\":\"1\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"payType\":null,\"monthDate\":null,\"payDays\":null,\"settle1\":null,\"settle2\":null,\"settle3\":null,\"remarks\":null},\"discountCategory\":{\"id\":\"1720265465225183234\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"discountCategory\":null,\"discountRate\":null},\"discountRate\":\"80\",\"isIncludingPriceTax\":\"0\",\"deliveryTerms\":\"交易条款\",\"remarks\":\"备注\",\"examineTime\":null,\"examineStatus\":\"\",\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"updateByName\":null,\"creatorOfficeName\":null,\"creatorOfficeId\":null,\"closeStatus\":null,\"closeUserId\":null,\"closeUserName\":null,\"closeTime\":null,\"purchaseOrderDetailDTOList\":[{\"id\":null,\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":null,\"tenantDTO\":null,\"image\":null,\"currentRecordInfoList\":null,\"screens\":null,\"andOr\":null,\"purchaseOrder\":null,\"stockDocId\":\"1714454706863972354\",\"stockDocCode\":\"S11001000010\",\"stockDocName\":\"陶瓷销\",\"stockDocSku\":\"陶瓷，直径：1.6mm 长度：3.7mm\",\"unit\":\"袋\",\"quantity\":\"15\",\"singleWeight\":null,\"totalWeight\":null,\"unitPriceWithoutTax\":\"486.7257\",\"unitPriceIncludingTax\":\"550\",\"warehouseId\":null,\"expectedDeliveryDate\":null,\"manufacturerConfirmDate\":null,\"warehouseCode\":null,\"warehouseName\":null,\"currentInventory\":null,\"requisitionNumber\":null,\"sourceSalesOrderNumber\":null,\"workOrderNumber\":null,\"receivedQuantity\":null,\"receivedReturnQuantity\":null,\"receiptQuantity\":null,\"giftQuantity\":null,\"giftReceiptQuantity\":null,\"warehouseReturnQuantity\":null,\"returnQuantity\":null,\"replenishmentQuantity\":null,\"foreignCurrencyTaxfreeAmount\":\"7300.8855\",\"foreignCurrencyTaxAmount\":\"949.1151\",\"totalForeignCurrencyPriceTax\":\"8250.0006\",\"localCurrencyTaxfreeAmount\":\"7300.8855\",\"localCurrencyTaxAmount\":\"949.1151\",\"totalLocalCurrencyPriceTax\":\"8250.0006\",\"examineStatus\":null}],\"processRecordList\":null,\"fileList\":[]}";
	//strJson = replace_all(strJson, "\n", "\r");
	//cPurPurchaseOrder* aaa = new cPurPurchaseOrder("1", strJson);
	//PSendDataMQ pSendMQ = aaa->CreateFilePDF();
	//delete aaa;

	//string sreData = "{\"type\":\"bomwh\",\"processId\":\"1742460506265792514\"}";
	//time_t now = time(0);
	//cDocumentCover* ClassPDF_DocumentCover = new cDocumentCover(to_string(now), sreData);
	//ClassPDF_DocumentCover->CreateFilePDF(0);
	//delete ClassPDF_DocumentCover;

	//string strJson = "{\"id\":\"1744989155758084097\",\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":null,\"tenantDTO\":null,\"image\":null,\"customFields\":null,\"currentRecordInfoList\":[],\"screens\":null,\"andOr\":null,\"code\":\"AdminXS202401018\",\"billDate\":\"2024-01-10\",\"processRecordList\":[],\"examineTime\":null,\"examineStatus\":\"0\",\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":\"管理员\",\"creatorUserId\":\"1\",\"updateByName\":null,\"creatorOfficeName\":\"行政部\",\"creatorOfficeId\":\"1563003414059802625\",\"closeUserId\":null,\"closeUserName\":null,\"closeTime\":null,\"closeStatus\":null,\"fileList\":[],\"custOrderNo\":\"021458752\",\"orderCate\":{\"id\":\"1721725873521848322\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":\"021\",\"name\":\"类别2\",\"prefix\":null},\"validDate\":\"2024-01-18\",\"customer\":{\"id\":\"1739850071019577346\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":\"002\",\"name\":\"安徽宁远医药有限公司\",\"shortName\":null,\"englishName\":null,\"taxId\":null,\"status\":null,\"salesmanId\":null,\"bkAccountGroup\":null,\"currencyRateId\":null,\"payTermsId\":null,\"taxRateId\":null,\"openAccountBank\":null,\"bankAccount\":null,\"deliveryWayId\":null,\"pricingMethod\":null,\"tradeClause\":null,\"discountCategoryId\":null,\"companyAddress\":null,\"invoiceAddress\":null,\"postcode\":null,\"companyWebsite\":null,\"dutyPerson\":null,\"dutyPersonEmail\":null,\"phoneOne\":null,\"phoneTwo\":null,\"contactPerson\":null,\"faxOne\":null,\"faxTwo\":null,\"remarks\":null,\"type\":null,\"clientClassificationId\":null,\"examineTime\":null,\"examineStatus\":null,\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"creatorOfficeName\":null,\"creatorOfficeId\":null,\"updateByName\":null,\"email\":null},\"salesDept\":{\"id\":\"1567336026660151297\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"parentId\":null,\"parentIds\":null,\"name\":\"一科室\",\"sort\":null,\"children\":null,\"legalPerson\":null,\"code\":\"0100101\",\"type\":null,\"grade\":null,\"address\":null,\"master\":null,\"phone\":null,\"useable\":null,\"departmentNum\":null,\"remarks\":null,\"productionUnit\":null},\"salesman\":{\"id\":\"1721724398649372673\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"name\":\"王五\",\"phone\":null,\"status\":null,\"tel\":null,\"fax\":null,\"email\":null,\"companyId\":null,\"officeId\":null,\"userId\":null},\"currency\":{\"id\":\"1740261134249721858\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"name\":\"韩元\",\"symbol\":null,\"digit\":null,\"remarks\":null},\"exchangeRate\":\"0.0055\",\"creditLimitPass\":\"1\",\"taxrate\":{\"id\":\"1719298788706713601\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"taxRate\":\"0.03\",\"remarks\":null},\"onTaxprice\":\"1\",\"payMethod\":{\"id\":\"1\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"payType\":\"款到发货\",\"monthDate\":null,\"payDays\":null,\"settle1\":null,\"settle2\":null,\"settle3\":null,\"remarks\":null},\"discountCate\":{\"id\":\"1719963259083128833\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"discountCategory\":\"98折\",\"discountRate\":\"98\"},\"shipMark\":\"啊啊啊啊啊\",\"recAddr\":{\"id\":\"1739850657727209474\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"code\":null,\"address\":\"深圳市南山区\",\"contactPerson\":null,\"phone\":null},\"transTerms\":\"条款\",\"remarks\":\"备注\",\"salesOrderEntryDTOList\":[{\"id\":null,\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":null,\"tenantDTO\":null,\"image\":null,\"customFields\":null,\"currentRecordInfoList\":[],\"screens\":null,\"andOr\":null,\"bill\":null,\"seq\":1,\"examineStatus\":\"0\",\"code\":\"AdminXS202401018\",\"billDate\":\"2024-01-10\",\"stock\":{\"id\":\"1727960665213026306\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"codeCategoryName\":null,\"ruleCode\":null,\"stockCode\":\"F0121031180200001C\",\"name\":\"多功能手术刀\",\"shortName\":null,\"packageDesc\":null,\"originalFactoryCode\":null,\"halfCode\":null,\"sku\":\"CPs001\",\"productSku\":null,\"basicUnitId\":null,\"basicUnitName\":null,\"saleUnitId\":null,\"saleUnitName\":null,\"isWeight\":null,\"stockLevel\":null,\"categoryId\":null,\"shuoming\":null,\"registerNumber\":null,\"stockDo\":null,\"procure\":null,\"sale\":null,\"produceComplete\":null,\"subcontract\":null,\"procureProcessId\":null,\"produceProcessId\":null,\"subcontractProcessId\":null,\"basicUnitWeight\":null,\"singleRongji\":null,\"singleTiji\":null,\"barNumber\":null,\"engineerNumber\":null,\"customsNumber\":null,\"isBackflush\":null,\"principle\":null,\"minQty\":null,\"lossRateType\":null,\"increaseQty\":null,\"dhMethod\":null,\"minDhBatch\":null,\"increaseBatch\":null,\"blMethod\":null,\"qdMethod\":null,\"leadtime\":null,\"minStock\":null,\"maxStock\":null,\"dailyProduction\":null,\"supplierId\":null,\"singleHours\":null,\"standardCosts\":null,\"isBatch\":null,\"batchRuleId\":null,\"isExpiry\":null,\"isSerial\":null,\"isChange\":null,\"expiry\":null,\"expiryUnit\":null,\"stockBookkeepCategoryId\":null,\"lossRateMethod\":null,\"productMark\":null,\"middleBoxMark\":null,\"outerBoxMark\":null,\"quickCode\":null,\"smallPackage\":null,\"middlePackage\":null,\"isSterilization\":null,\"isCustom\":null,\"saleType\":null,\"conversion\":null,\"remarks\":null,\"setBatchRuleId\":null,\"batchRuleCategoryId\":null,\"isUse\":null,\"isSet\":null,\"examineTime\":null,\"examineStatus\":null,\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"updateByName\":null,\"isCreate\":null,\"isZutao\":null,\"bookLanguage\":null,\"effectiveYear\":null,\"tradeName\":null,\"tradeDescribe\":null,\"udiDi\":null,\"serialRuleId\":null,\"isDiUse\":null,\"isCreatSerial\":null,\"isLabelUse\":null},\"sterilization\":\"1\",\"unit\":{\"id\":\"1716736525508534274\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"name\":\"M\",\"digit\":null,\"remarks\":null},\"weight\":null,\"totalWeight\":null,\"conversion\":null,\"qty\":\"130\",\"volume\":null,\"price\":\"485.4369\",\"taxPrice\":\"500\",\"amount\":\"63106.7970\",\"tax\":\"1893.2039\",\"taxAmount\":\"65000.0009\",\"baseAmount\":\"347.0874\",\"baseTax\":\"10.4126\",\"baseTaxAmount\":\"357.5000\",\"writtenOff\":\"0\",\"curSku\":\"875.0\",\"planCommitTime\":null,\"factoryConfirmTime\":null,\"regisNo\":null,\"transWay\":null,\"applyPreRecAmt\":\"0\",\"preRecAmt\":\"0\",\"canPreRecAmt\":\"0\",\"unPreRecAmt\":\"0\",\"attachComment\":null,\"canShipQty\":\"130\",\"canTransferQty\":\"130\",\"bomId\":null,\"bomRev\":null,\"isOrderBom\":null,\"isChange\":null,\"startDate\":null,\"endDate\":null,\"shippedQty\":\"0\",\"infoStatus\":\"1\"}],\"isOrderUse\":null,\"amount\":\"61844.6611\",\"tax\":\"1855.3398\",\"taxAmount\":\"63700.0009\",\"baseAmount\":\"340.1457\",\"baseTax\":\"10.2043\",\"baseTaxAmount\":\"350.3500\",\"new\":true}";
	//strJson = replace_all(strJson, "\n", "\r");
	//time_t now = time(0);
	//cLibFather* ClassPDF = new cSalSalesorder("xsdd", to_string(now), strJson);
	//PSendDataMQ pSendMQ = ClassPDF->CreateFilePDF();
	//delete ClassPDF;

	//string strJson = "{\"id\":\"1747161608794017794\",\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":null,\"tenantDTO\":null,\"image\":null,\"customFields\":null,\"currentRecordInfoList\":[],\"screens\":null,\"andOr\":null,\"isDataAuth\":null,\"number\":null,\"completeDate\":\"2024-01-16\",\"unitDocId\":\"1726564240277258242\",\"unitDocNumber\":\"001\",\"unitDocName\":\"001包装车间\",\"isPiece\":\"1\",\"examineTime\":null,\"examineStatus\":\"0\",\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"updateByName\":null,\"remarks\":\"备注信息\",\"productionCompleteDetailDTOList\":[{\"id\":null,\"createTime\":null,\"createBy\":null,\"updateTime\":null,\"updateBy\":null,\"delFlag\":0,\"tenantDTO\":null,\"image\":null,\"customFields\":\"[{\"id\":\"1739946909612642306\",\"delFlag\":0,\"isDataAuth\":null,\"name\":\"字段1\",\"isRequired\":\"0\",\"dataType\":\"0\",\"selectFields\":\"\",\"type\":\"0\"},{\"id\":\"1739946914121519106\",\"delFlag\":0,\"isDataAuth\":null,\"name\":\"字段1\",\"isRequired\":\"0\",\"dataType\":\"0\",\"selectFields\":\"\",\"type\":\"1\"}]\",\"currentRecordInfoList\":[],\"screens\":null,\"andOr\":null,\"isDataAuth\":null,\"complete\":null,\"workOrder\":{\"id\":\"1746811954038489090\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"number\":null,\"planDate\":null,\"mplanNo\":null,\"processLineCode\":null,\"isSterilization\":null,\"spId\":null,\"spNo\":null,\"spName\":null,\"mpcName\":null,\"mpcId\":null,\"saleType\":null,\"spSpec\":null,\"orderVersion\":null,\"isCustomized\":null,\"spaddName\":null,\"planId\":null,\"effectiveYear\":null,\"mkId\":null,\"mkName\":null,\"bomRev\":null,\"osTime\":null,\"mmlQuan\":null,\"hideMmlQuan\":null,\"planQuan\":null,\"pstartDate\":null,\"pendDate\":null,\"trQuan\":null,\"scrapQuan\":null,\"mpackageQuan\":null,\"khId\":null,\"khNo\":null,\"khName\":null,\"khSname\":null,\"ssoId\":null,\"ssoNos\":null,\"inQuan\":null,\"expackageQuan\":null,\"fgoodsNo\":null,\"hgoodsNo\":null,\"packageNo\":null,\"bookLanguage\":null,\"spEname\":null,\"notes\":null,\"isStores\":null,\"examineTime\":null,\"examineStatus\":null,\"examineUserName\":null,\"examineUserId\":null,\"creatorUserName\":null,\"creatorUserId\":null,\"updateByName\":null,\"maxCompleteQty\":null,\"reMmlQuan\":null,\"isRe\":null,\"orderType\":null,\"bomId\":null,\"isInventory\":null,\"isAdduct\":null,\"unitName\":null,\"smallPackage\":null,\"basicUnitWeight\":null,\"isBatch\":null,\"batchNumberId\":null,\"warehouseBatchId\":null,\"bomType\":null,\"saleUnitId\":null,\"saleUnitName\":null,\"conversion\":null,\"custOrderNo\":null,\"seq\":null,\"planCommitTime\":null,\"closeStatus\":null,\"closeUserId\":null,\"closeUserName\":null,\"closeTime\":null,\"lockVersion\":null,\"produceProcessId\":null,\"customFields\":null,\"muQuan\":null},\"workOrderNumber\":\"Admin-_GLD20240100157\",\"stockDocId\":\"1727965131832213506\",\"spNo\":\"SBM11024\",\"spName\":\"注塑钨丝电极组件\",\"spSpec\":\"20*13mm环形,黄色,移印钨丝尺寸\",\"spAddName\":null,\"unitName\":\"M\",\"planQuan\":\"4100\",\"completeQuan\":\"3987\",\"hideCompleteQuan\":\"3987\",\"sterilizationNo\":\"12412341235412\",\"totalWeight\":\"31896.0000\",\"completeReturnQty\":null,\"receiptQty\":null,\"completeScrapQty\":null,\"warehouseBatchId\":\"8a3f174df53bb3726f924818f461d24a\",\"batchNumber\":null,\"beginProduceDate\":null,\"endValidityDate\":null,\"resourceDocId\":null,\"resourceDocName\":null,\"realityWorkTime\":null,\"ssoNos\":null,\"scpNos\":null,\"examineStatus\":null,\"sort\":null,\"remarks\":null,\"mplanNo\":null,\"beforeCompleteQuan\":\"0\",\"number\":\"Admin-_GLD20240100157\",\"completeDate\":null,\"expiry\":null,\"expiryUnit\":null,\"isBatch\":\"1\",\"batchRuleId\":\"1720722848309248002\",\"singleRongji\":null,\"basicUnitWeight\":\"8\",\"managementId\":\"1717151121446424577\",\"managementCode\":\"0001\",\"managementName\":\"储位一号\",\"warehouseId\":\"1717140914224123906\",\"warehouseCode\":\"001\",\"warehouseName\":\"北京仓库\",\"warehouseType\":null,\"baseBatchNumber\":{\"id\":\"1746811953795219457\",\"createTime\":null,\"createById\":null,\"updateTime\":null,\"updateById\":null,\"delFlag\":null,\"tenantId\":null,\"docId\":null,\"batchNumber\":\"2429150334\",\"produceDate\":\"2024-01-15\",\"endDate\":\"2115-09-15\",\"inventory\":null,\"remarks\":null},\"khId\":null,\"khNo\":null,\"khName\":null,\"produceProcessId\":\"12\",\"isSerial\":\"0\",\"serialRuleId\":null}],\"processRecordList\":null,\"fileList\":[],\"lockVersion\":null}";
	//strJson = replace_all(strJson, "\n", "\r");
	//time_t now = time(0);
	//cLibFather* ClassPDF = new cMpsProductionComplete("scwgd", to_string(now), strJson);
	//PSendDataMQ pSendMQ = ClassPDF->CreateFilePDF();
	//delete ClassPDF;

	//string Data = "{\"type\":\"zdwj\",\"processId\":\"1743480049901670401\"}";
	//time_t now = time(0);
	//cDocumentCover* ClassPDF_DocumentCover = new cDocumentCover(to_string(now), Data);
	//ClassPDF_DocumentCover->CreateFilePDF(0);
	//delete ClassPDF_DocumentCover;

	//string sreData = "{\"labelId\":\"36\",\"udiId\":\"1743237935410393090\",\"mark0\":\"(01)22633698100028\",\"piBatchNumber\":\"(10)2415050244\",\"piProduceDate\":\"(11)2024-01-05\",\"piEndDate\":\"(17)2024-07-05\",\"piSerialNumber\":\"(21)ZYSPCE2024010500028\",\"type\":\"label\"}";
	//time_t now = time(0);
	//cLabel* ClassPDF_label = new cLabel(to_string(now), sreData);
	//ClassPDF_label->CreateFilePDF();
	//delete ClassPDF_label;
	/*
	
	{"type":"bomwh","processId":"1743539246580310017"}
	*/

	SaveLog("main", "程序启动");
	CNGLock* pLock = new CNGLock;
	PSendDataMQ pHead = new SendDataMQ;
	pHead->Data = "测试";
	PThreadParameter pData = new ThreadParameter;
	pData->pHeadMQ = pHead;
	pData->pLock = pLock;
	//注册报错回调函数
	SetUnhandledExceptionFilter(callback);
	//启动服务端线程
	HANDLE hThread_Sign = CreateThread(NULL, 0, Thread_accept, (LPVOID)pData, 0, NULL);
	//启动MQ进程
	cRabbitMQ* pClass_MQ = new cRabbitMQ(pLock, pHead);

	pClass_MQ->recv_start();//启动接收
	pClass_MQ->send_start();//启动发送

	////测试文件生成流程代码
	//string strJson = "{\"type\":\"zgglz\",\"body\":{\"id\":\"1721356389208485890\",\"createTime\":1699238319120,\"createById\":\"1\",\"updateTime\":1699238319141,\"updateById\":\"1\",\"delFlag\":0,\"tenantId\":\"10000\",\"number\":\"Admin-HGFZR23110019\",\"docId\":\"1721341208181063682\",\"no\":\"AAAAAAAAA|000000036|\",\"name\":\"张三\",\"officeName\":\"财务部\",\"postName\":\"财务主管\",\"appointDate\":\"2023-11-16\",\"deputyDate\":\"2023-11-25\",\"authority\":\"1、全面领导公司的日常工作，向公司传达满足顾客要求和法规要求的重要性\n2、制定、颁布质量方针和质量目标，并对质量目标是否满足产品要求、是否在相关职能和层次上展开负责\n3、按GMP、GB/T19001 (IDT IS019001) 、YY/T0287 (IDT ISO13485) 、MDR (2017/745/UE) 、EN IS013485: 2016、QSR820标准建立质量体系，批准质量手册4、按策划的时间间隔开展管理评审,评审质量管理体系，以确保其持续的适宜性、充分性和有效性。\n3、确保在公司内建立适当的沟通过程，并且确保对品质管理的有效性进行沟通\n4、确保公司内部的职责、权限得到规定和沟通\n5、确保对质量管理体系进行策划，以及在对质量管理体系的变更进行策划和实施，保持质量管理体系的完整性。\n6、确保获得与建立、实施和持续改进质量管理体系有效性有关的资源\n7、任命管理者代表与合规负责人\n8、对所有出厂产品的质量负主要责任\n9、确保企业按照法律、法规和规章的要求组织生产\",\"state\":null,\"isBegin\":\"0\",\"examineTime\":null,\"examineStatus\":\"0\",\"examineUserName\":null,\"examineUserId\":\"1718088301314715649\",\"creatorUserName\":\"管理员\",\"creatorUserId\":\"1\",\"creatorOfficeName\":\"行政部\",\"creatorOfficeId\":\"1563003414059802625\",\"remarks\":null},\"userId\":\"1\",\"userName\":\"管理员\"}";
	//cAppointManager* aaa = new cAppointManager("1", strJson);
	//PSendDataMQ pSendMQ = aaa->CreateFilePDF();
	//pLock->Lock();
	//pSendMQ->pNext = pHead->pNext;
	//pHead->pNext = pSendMQ;
	//pLock->Unlock();

	getchar();
	delete pClass_MQ;
	delete pLock;
	SaveLog("main", "程序关闭");
}